/*------------------------------------------------------------------------
//                          Project CommonLib                           //
------------------------------------------------------------------------*/

#include "stdafx.h"
#include "BitCheck.h"

namespace BitCheck
{
    #define BITFLAG 0x01
    #define BITCHECK(val, bit)  ((val>>bit)&BITFLAG)   
    #define BYTEBIT 8
	    
     void SetBit(char* orgVal, const DWORD& bitPos)
    {
        char *orgChar=NULL;
        DWORD posBit=0;
        if( bitPos>BYTEBIT )
        {
            const DWORD posByte = bitPos/BYTEBIT;
            if( 0==(bitPos%BYTEBIT) )
            {                
                posBit = 7;
                orgChar= (orgVal+posByte-1);
            }
            else
            {                
                posBit = (bitPos%BYTEBIT)-1;
                orgChar= (orgVal+posByte);
            }
            
        }
        else
        {
            posBit  = bitPos-1;
            orgChar = orgVal;            
        }

        (*orgChar)|=BITFLAG<<(posBit);    
    }

     void UnsetBit(char* orgVal, const DWORD& bitPos)
    {
        char *orgChar=NULL;
        DWORD posBit=0;
        if( bitPos>BYTEBIT )
        {
            const DWORD posByte = bitPos/BYTEBIT;
            if( 0==(bitPos%BYTEBIT) )
            {                
                posBit = 7;
                orgChar= (orgVal+posByte-1);
            }
            else
            {                
                posBit = (bitPos%BYTEBIT)-1;
                orgChar= (orgVal+posByte);
            }
        }
        else
        {
            posBit  = bitPos-1;
            orgChar = orgVal;            
        }

        (*orgChar) &= ~(BITFLAG<<(posBit));
    }

    bool CheckBit(char* orgVal, const DWORD& bitPos)
    {
        char *orgChar=NULL;
        DWORD posBit=0;
        if(bitPos>BYTEBIT)
        {
            const DWORD posByte = bitPos/BYTEBIT;
            if( 0==(bitPos%BYTEBIT) )
            {                
                posBit = 7;
                orgChar= (orgVal+posByte-1);
            }
            else
            {                
                posBit = (bitPos%BYTEBIT)-1;
                orgChar= (orgVal+posByte);
            }            
        }
        else
        {
            posBit  = bitPos-1;
            orgChar = orgVal;
        }

        return BITCHECK(*orgChar, posBit);    
    }

}


/*------------------------------------------------------------------------

------------------------------------------------------------------------*/
